package Bestv.OTT_B2B_Replay;
import java.nio.FloatBuffer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.apache.storm.command.rebalance;
import org.apache.storm.shade.clojure.tools.macro__init;
import org.json.simple.JSONObject;
import com.google.gson.JsonObject;
import com.sun.javafx.collections.MappingChange.Map;

import javassist.expr.NewArray;
import scala.annotation.elidable;
/*
 *  解析nginx日志,并将其格式化json类型，便于传递
 * @
 */
public class Nginx_Access_Resolve {
	private String nginx_log;
	/*private String type;
	private String sate;
	private String remote_ip;
	private String remote_port;
	private String hostname;
	private String log_time;*/
	private String request_method;
	private String request_body;
	private String http_version;
	private String http_referer;
	private  Float upstream_response_time;
	private  Float body_bytes_sent;
	/*private String upstream_addr;
	private Float upstream_response_time;
	private Float body_bytes_sent;
	
	private String http_user_agent;
	private String http_x_forwarded_for;
	private String status;
	private Float request_time;
	public Float upstream_response_time;
	public Float body_bytes_sent;*/
	public JSONObject log_json=new JSONObject();
	public java.util.Map<String, Object> log_map=new HashMap<>();
	Logger logger=Logger.getLogger(Nginx_Access_Resolve.class);
	
	public Nginx_Access_Resolve(String nginx_log) {
		// TODO Auto-generated constructor stub
		this.nginx_log=nginx_log;
	}
	
	/**
	 * to format string as date timestamp for es
	 * @param timestamp
	 * @return
	 */
	public String module_type() {
		GetPropertiesItems storm_properties=new GetPropertiesItems("/opt/storm/apache-storm-1.0.1/work/OTT-B2B-REPLAYEPG/storm.properties");
		return storm_properties.ReadProperty("type");
	}
	
	public java.util.Date GetTimestamp(String timestamp) {
		
		//定义日期格式
		//dd/MMM/yyyy:hh:mm:ss Z
		String pattern = "dd/MMM/yyyy:hh:mm:ss Z";
		SimpleDateFormat dateformat=new SimpleDateFormat(pattern,Locale.ENGLISH);
		java.util.Date timestamp_format=new java.util.Date();	
		
		try {
			java.util.Date timestamp_format1=dateformat.parse(timestamp);
			timestamp_format=timestamp_format1;
			timestamp_format1=null;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			return timestamp_format;		
	}
	
	/*
	 * 获取时间建立index每天的_type
	 */
	public String type_time(Date time) {
		SimpleDateFormat time_format=new SimpleDateFormat("yyyy-MM-dd");
		String type_time=time_format.format(time);
		if (type_time.isEmpty()) {
			//返回当前系统时间时间
			return time_format.format(new Date());
		}else {
			//返回日志的时间的yyyy-MM-dd
			return type_time;
		}
		
	}
	
	
	
	
	
	public boolean IsHasNum(String str) {
		Pattern pattern = Pattern.compile("[0-9.]*"); 
		Matcher isHasNum = pattern.matcher(str);
		   if( ! isHasNum.matches() ){
		       return false; 
		   } 
		   return true; 
	}
	
	
		

	public JSONObject nginx_resolve(){
		
		if (nginx_log.length() >= 200) {
			try {
			if (nginx_log.split("\\|").length > 5) {
				String type=nginx_log.split("\\|")[2].toLowerCase();
				String sate=nginx_log.split("\\|")[3].toLowerCase();
				String log_message1=nginx_log.split("\\|")[5];
				if (log_message1.split(" - ").length >= 1) {
					String log_message2=log_message1.split(" - ")[0];
					if ((log_message2.split(" ").length >= 4) && (log_message2.split(" ")[4]).length() > 10) {		
						
						//String remote_ip=log_message2.split(" ")[4].split(":")[0];
						//int remote_port=Integer.parseInt(log_message2.split(" ")[4].split(":")[1]);
						//String hostname=log_message2.split(" ")[3].split("\\@")[0];
						if ( log_message2.split("\\@").length ==2 ) {
							if (log_message2.split("\\@")[1].split(" ").length ==2 ) {
								String remote_ip=log_message2.split("\\@")[1].split(" ")[1].split(":")[0];
								int remote_port=Integer.parseInt(log_message2.split("\\@")[1].split(" ")[1].split(":")[1]);
								String hostname=log_message2.split("\\@")[1].split(" ")[0];
									if ((log_message1.split(" - \\[").length) > 1 && log_message1.length() > 120) {
											String log_message3=log_message1.split(" - \\[")[1];
											//if ((log_message3.split("\\] ")[1].split(" ")[0].length()) > 10) {				
											String log_time=log_message3.split("\\] ")[0];
											Date time= GetTimestamp(log_time);
											log_time=null;
							
												if ((log_message3.split("\\] ")[1].split(" ")).length >= 9) {
														if (log_message3.split("\\] ")[1].split(" ")[0].length() == 3) {
															request_method="-";
															request_body="-";
															http_version="-";
														}else{
															request_method=log_message3.split("\\] ")[1].split(" ")[0].substring(1,(log_message3.split("\\] ")[1].split(" ")[0].length()));
															request_body= log_message3.split("\\] ")[1].split(" ")[1];
															http_version=log_message3.split("\\] ")[1].split(" ")[2].substring(0, ((log_message3.split("\\] ")[1].split(" ")[2]).length()-1));					
														}
												String upstream_addr=log_message3.split("\\] ")[1].split(" ")[3];
												//upstream_response_time=Float.parseFloat(log_message3.split("\\] ")[1].split(" ")[4]);
												//body_bytes_sent=Float.parseFloat(log_message3.split("\\] ")[1].split(" ")[5]);
												String  upstream_response_time_tmp=log_message3.split("\\] ")[1].split(" ")[4];		
												String  body_bytes_sent_tmp=log_message3.split("\\] ")[1].split(" ")[5];
												if ( ! IsHasNum(upstream_response_time_tmp) ) {
													upstream_response_time=Float.parseFloat("0");
												}else {
													upstream_response_time=Float.parseFloat(upstream_response_time_tmp);
												}
												if (! IsHasNum(body_bytes_sent_tmp)) {
													body_bytes_sent=Float.parseFloat("0");
								
												}else {
													body_bytes_sent=Float.parseFloat(body_bytes_sent_tmp);
												}
												upstream_response_time_tmp=null;
												body_bytes_sent_tmp=null;
												if ((log_message3.split("\\] ")[1].split(" ")[6]).length() > 1) {
													http_referer=log_message3.split("\\] ")[1].split(" ")[6].substring(1, (log_message3.split("\\] ")[1].split(" ")[6].length()-1));
												}else {
													http_referer=log_message3.split("\\] ")[1].split(" ")[6];
												}
							
												String log_message4=log_message3.split("\" \"")[1];
												String http_user_agent = log_message4.split("\" ")[0];
												String http_x_forwarded_for =log_message4.split("\" ")[1].split(" ")[0];
												int status = Integer.parseInt(log_message4.split("\" ")[1].split(" ")[1]);
												//String request_time = log_message4.split("\" ")[1].split(" ")[2];
												Float request_time = Float.parseFloat(log_message4.split("\" ")[1].split(" ")[2]);
												log_map.put("_index", sate+"-"+module_type());
												log_map.put("_type",module_type()+"-"+type_time(time));
												log_map.put("type",type);
												log_map.put("remote_ip", remote_ip);
												log_map.put("remote_port", remote_port);
												log_map.put("hostname", hostname);
												log_map.put("@timestamp", time);
												log_map.put("request_method", request_method);
												log_map.put("request_body", request_body);
												log_map.put("http_version",http_version);
												log_map.put("upstream_addr",upstream_addr);
												log_map.put("upstream_response_time",upstream_response_time);
												log_map.put("body_bytes_sent",body_bytes_sent);
												log_map.put("http_referer",http_referer);
												log_map.put("http_user_agent",http_user_agent);
												log_map.put("http_x_forwarded_for",http_x_forwarded_for);
												log_map.put("status", status);
												log_map.put("request_time",request_time );
												log_json.putAll(log_map);
												}
										}
							}else {
								logger.warn("nginx_log format is not normal,connot resolve");
								logger.warn("Not Normal Format Nginx Log Is: "+nginx_log);
						}
								
				}else {
					logger.warn("nginx_log format is not normal,connot resolve");
					logger.warn("Not Normal Format Nginx Log Is: "+nginx_log);
				}
				
				}
					
				}else {
					logger.warn("nginx_log format is not normal,connot resolve");
					logger.warn("Not Normal Format Nginx Log Is: "+nginx_log);
				}	
				
				
			}else {
				logger.warn("nginx_log format is not normal,connot resolve");
				logger.warn("Not Normal Format Nginx Log Is: "+nginx_log);
				
			}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				logger.error("Nginx_Access_Resolve.nginx_resolve, Get an Exception: \n"+"Not Normal log_message is:\n"+nginx_log, e); 
				
		}
	}else {
			logger.warn("nginx_log format is not normal ,connot resolve");
			logger.warn("Not Normal Format Nginx Log Is: "+nginx_log);
			
		}
		
		return log_json;
	}	
}
